/**
 * @file protocol_adapters.c
 * @brief 协议适配器实现
 * @details 实现不同协议（104、3761、3762）的适配器，用于消息分发器
 */

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include "../include/data_dispatcher.h"
#include "../../../common/json/include/json_utils.h"
#include "../../../common/logs/include/logger.h"
#include "../../../../protocol/104/core/api/include/protocol_interface.h"

#define LOG_MODULE_NAME "PROTOCOL_ADAPTERS"

/* ==================== 104协议适配器 ==================== */

/**
 * @brief 104协议适配器句柄
 */
typedef struct {
    protocol_handle_t protocol_handle;  /* 104协议句柄 */
} adapter_104_handle_t;

/**
 * @brief 104协议适配器初始化
 */
static void* adapter_104_init(const char* config) {
    LOG_INFO(LOG_MODULE_NAME, "初始化104协议适配器");
    
    adapter_104_handle_t* handle = (adapter_104_handle_t*)calloc(1, sizeof(adapter_104_handle_t));
    if (handle == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "内存分配失败");
        return NULL;
    }
    
    // TODO: 从配置中读取104协议参数
    // 目前使用默认配置
    protocol_config_t protocol_config = {0};
    // protocol_config.server_ip = "192.168.1.100";
    // protocol_config.server_port = 2404;
    // protocol_config.common_address = 1;
    // protocol_config.timeout_ms = 3000;
    // protocol_config.auto_reconnect = true;
    
    // handle->protocol_handle = protocol_create(&protocol_config);
    // if (handle->protocol_handle == NULL) {
    //     LOG_ERROR(LOG_MODULE_NAME, "104协议创建失败");
    //     free(handle);
    //     return NULL;
    // }
    
    LOG_INFO(LOG_MODULE_NAME, "104协议适配器初始化成功");
    return handle;
}

/**
 * @brief 104协议适配器清理
 */
static void adapter_104_cleanup(void* handle) {
    if (handle == NULL) {
        return;
    }
    
    adapter_104_handle_t* adapter = (adapter_104_handle_t*)handle;
    
    if (adapter->protocol_handle != NULL) {
        // protocol_disconnect(adapter->protocol_handle);
        // protocol_destroy(adapter->protocol_handle);
    }
    
    free(adapter);
    LOG_INFO(LOG_MODULE_NAME, "104协议适配器已清理");
}

/**
 * @brief 104协议适配器发送数据
 */
static int adapter_104_send_data(void* handle, const char* data_json) {
    if (handle == NULL || data_json == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "参数为空");
        return -1;
    }
    
    adapter_104_handle_t* adapter = (adapter_104_handle_t*)handle;
    
    // 解析JSON数据
    void* json_obj = json_utils_parse(data_json);
    if (json_obj == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "JSON解析失败");
        return -1;
    }
    
    // 提取数据字段并转换为104协议格式
    // TODO: 根据实际的JSON格式提取数据
    // 示例：假设JSON格式为 {"address": 1001, "type": "measurement", "value": 123.45}
    
    void* address_item = json_utils_get_object_item(json_obj, "address");
    void* value_item = json_utils_get_object_item(json_obj, "value");
    
    if (address_item == NULL || value_item == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "缺少必要的字段");
        json_utils_delete(json_obj);
        return -1;
    }
    
    uint32_t address = (uint32_t)json_utils_get_number_value(address_item);
    float value = (float)json_utils_get_number_value(value_item);
    
    // 构造104协议数据点
    data_point_t data_point = {0};
    data_point.address = address;
    data_point.type = DATA_TYPE_MEASUREMENT;
    data_point.quality = DATA_QUALITY_GOOD;
    data_point.timestamp = time(NULL) * 1000;
    data_point.value.measurement = value;
    
    // 发送数据（暂时注释，因为protocol_handle可能为NULL）
    // send_result_t result = protocol_send_data(adapter->protocol_handle, &data_point);
    // if (result != SEND_RESULT_SUCCESS) {
    //     LOG_ERROR(LOG_MODULE_NAME, "104协议发送失败: %d", result);
    //     json_utils_delete(json_obj);
    //     return -1;
    // }
    
    json_utils_delete(json_obj);
    
    LOG_DEBUG(LOG_MODULE_NAME, "104协议数据发送成功: 地址=%u, 值=%.2f", address, value);
    return 0;
}

/* ==================== 3761协议适配器 ==================== */

/**
 * @brief 3761协议适配器句柄
 */
typedef struct {
    void* protocol_handle;  /* 3761协议句柄（待实现） */
} adapter_3761_handle_t;

/**
 * @brief 3761协议适配器初始化
 */
static void* adapter_3761_init(const char* config) {
    LOG_INFO(LOG_MODULE_NAME, "初始化3761协议适配器");
    
    adapter_3761_handle_t* handle = (adapter_3761_handle_t*)calloc(1, sizeof(adapter_3761_handle_t));
    if (handle == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "内存分配失败");
        return NULL;
    }
    
    // TODO: 实现3761协议的初始化
    // handle->protocol_handle = dlt3761_create(config);
    
    LOG_INFO(LOG_MODULE_NAME, "3761协议适配器初始化成功");
    return handle;
}

/**
 * @brief 3761协议适配器清理
 */
static void adapter_3761_cleanup(void* handle) {
    if (handle == NULL) {
        return;
    }
    
    adapter_3761_handle_t* adapter = (adapter_3761_handle_t*)handle;
    
    // TODO: 实现3761协议的清理
    // if (adapter->protocol_handle != NULL) {
    //     dlt3761_destroy(adapter->protocol_handle);
    // }
    
    free(adapter);
    LOG_INFO(LOG_MODULE_NAME, "3761协议适配器已清理");
}

/**
 * @brief 3761协议适配器发送数据
 */
static int adapter_3761_send_data(void* handle, const char* data_json) {
    if (handle == NULL || data_json == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "参数为空");
        return -1;
    }
    
    // TODO: 实现3761协议的数据发送
    // 1. 解析JSON数据
    // 2. 转换为3761协议格式
    // 3. 发送数据
    
    LOG_DEBUG(LOG_MODULE_NAME, "3761协议数据发送: %s", data_json);
    return 0;
}

/* ==================== 3762协议适配器 ==================== */

/**
 * @brief 3762协议适配器句柄
 */
typedef struct {
    void* protocol_handle;  /* 3762协议句柄（待实现） */
} adapter_3762_handle_t;

/**
 * @brief 3762协议适配器初始化
 */
static void* adapter_3762_init(const char* config) {
    LOG_INFO(LOG_MODULE_NAME, "初始化3762协议适配器");
    
    adapter_3762_handle_t* handle = (adapter_3762_handle_t*)calloc(1, sizeof(adapter_3762_handle_t));
    if (handle == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "内存分配失败");
        return NULL;
    }
    
    // TODO: 实现3762协议的初始化
    // handle->protocol_handle = dlt3762_create(config);
    
    LOG_INFO(LOG_MODULE_NAME, "3762协议适配器初始化成功");
    return handle;
}

/**
 * @brief 3762协议适配器清理
 */
static void adapter_3762_cleanup(void* handle) {
    if (handle == NULL) {
        return;
    }
    
    adapter_3762_handle_t* adapter = (adapter_3762_handle_t*)handle;
    
    // TODO: 实现3762协议的清理
    // if (adapter->protocol_handle != NULL) {
    //     dlt3762_destroy(adapter->protocol_handle);
    // }
    
    free(adapter);
    LOG_INFO(LOG_MODULE_NAME, "3762协议适配器已清理");
}

/**
 * @brief 3762协议适配器发送数据
 */
static int adapter_3762_send_data(void* handle, const char* data_json) {
    if (handle == NULL || data_json == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "参数为空");
        return -1;
    }
    
    // TODO: 实现3762协议的数据发送
    // 1. 解析JSON数据
    // 2. 转换为3762协议格式
    // 3. 发送数据
    
    LOG_DEBUG(LOG_MODULE_NAME, "3762协议数据发送: %s", data_json);
    return 0;
}

/* ==================== 适配器导出 ==================== */

/**
 * @brief 获取104协议适配器
 */
const protocol_adapter_t* get_adapter_104(void) {
    static protocol_adapter_t adapter = {
        .type = DISPATCH_PROTOCOL_104,
        .name = "IEC 60870-5-104",
        .init = adapter_104_init,
        .cleanup = adapter_104_cleanup,
        .send_data = adapter_104_send_data
    };
    return &adapter;
}

/**
 * @brief 获取3761协议适配器
 */
const protocol_adapter_t* get_adapter_3761(void) {
    static protocol_adapter_t adapter = {
        .type = DISPATCH_PROTOCOL_3761,
        .name = "DL/T 376.1",
        .init = adapter_3761_init,
        .cleanup = adapter_3761_cleanup,
        .send_data = adapter_3761_send_data
    };
    return &adapter;
}

/**
 * @brief 获取3762协议适配器
 */
const protocol_adapter_t* get_adapter_3762(void) {
    static protocol_adapter_t adapter = {
        .type = DISPATCH_PROTOCOL_3762,
        .name = "DL/T 376.2",
        .init = adapter_3762_init,
        .cleanup = adapter_3762_cleanup,
        .send_data = adapter_3762_send_data
    };
    return &adapter;
}
